package org.itboys.mobile.controller.mobile;

import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.dto.pay.SundayPayDto;
import org.itboys.mobile.service.mysql.mobile.pay.SundayMobilePayService;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.pay.alipay.AlipayWapResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月9日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_支付_controller。
 *
 */
@Controller
@RequestMapping("/sunday/mobile/pay")
public class SundayMobilePayController extends BaseController{
    @Autowired
    private SundayMobilePayService payService;



    /**
     *【用户版】预支付接口。请先创建订单后，再调用此接口
     * @param request
     * @param response
     * @param payType
     * @param orderIds
     * @param type
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/preparePay",method= RequestMethod.POST)
    @ApiOperation(value="【用户版】预支付接口。请先创建订单后，再调用此接口")
    public void preparePay(HttpServletRequest request,
             HttpServletResponse response,
            @ApiParam(required = true, name = "payType", value = "支付方式。1，支付宝，2微信") @RequestParam(value="payType",required=true) Integer payType,
            @ApiParam(required = true, name = "orderIds", value = "订单ID集合。以创建订单时返回的数据为准") @RequestParam(value="orderIds",required=true) List<Long> orderIds,
            @ApiParam(required = true, name = "type", value = "支付类型。1，订单支付，2钱包充值") @RequestParam(value="type",required=true) Integer type,

            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {

        try{
            Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
            param.put("payType", payType);
            StringBuilder orderIdsStr=new StringBuilder();
            for(Long orderId:orderIds){
                orderIdsStr.append(orderId+",");
            }
            param.put("orderIds",orderIdsStr.substring(0,orderIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
            param.put("type", type);
            param.put("nonce", nonce);
            param.put("sign", sign);
            /*boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            //Long memberId = AccountIdHoldUtils.getMemberId();
           /* SundayPayDto result = payService.preparePay(payType,orderIds,type);*/
            SundayPayDto result = payService.preparePay(payType,orderIds,type);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/pay/preparePay----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/callback/alipay", method={RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【用户版】支付回掉接口。由支付宝回掉，移动端忽略。。")
    public  void callback_alipay(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            AlipayWapResult alipayWapResult = payService.callback_alipay(request);
            if(alipayWapResult.isVerify_result()){
                AjaxUtils.renderJson(response, "success");
            }else{
                AjaxUtils.renderJson(response, "fail");
            }

        } catch (Exception e) {
            e.printStackTrace();

            logger.error("/sunday/mobile/pay/callback/alipay------"+e.getMessage());
            AjaxUtils.renderJson(response, "fail");
        }
    }
    @RequestMapping(value="/callback/wechat", method = {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【用户版】支付回掉接口。由微信回掉，移动端忽略。")
    public  void callback_wchat(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            String reuslt =payService.callback_wechat(request, response);
            AjaxUtils.renderJson(response, reuslt);
        } catch (Exception e) {
            e.printStackTrace();

            logger.error("/sunday/mobile/pay/callback/wechat------"+e.getMessage());
            AjaxUtils.renderJson(response, "fail");
        }
    }


}
